﻿using System;
using System.Windows.Forms;

namespace KstopaCommon
{
    public class AppStartHelper
    {
        /// <summary>
        /// 判断应用程序是否互斥
        /// </summary>
        /// <param name="productName">Application.ProductName</param>
        /// <returns></returns>
        public static bool IsMutex(string productName)
        {
            bool ret;
            using (System.Threading.Mutex mu = new System.Threading.Mutex(true, productName, out ret))
            {
                if (ret)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 绑定程序中的异常处理
        /// </summary>
        public static void BindExceptionHandler()
        {
            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            //①Application.ThreadException 事件--当UI线程中某个异常未被捕获时出现。
            //②AppDomain.UnhandledException 事件--当非UI线程中某个异常未被捕获时出现。

            //处理UI线程异常
            System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理未捕获的异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        /// <summary>
        /// 处理UI线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.Exception as Exception);
        }

        /// <summary>
        /// 处理未捕获的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.ExceptionObject as Exception);
        }

    }

}
